import { login, register, getUserInfo, getUserList, addUser, updateUser, deleteUser } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { logout } from '@/api/user'

const state = {
  token: getToken(),
  userInfo: null,
  userList: [],
  total: 0
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_USER_LIST(state, payload) {
    state.userList = payload.list
    state.total = payload.total
  }
}

const actions = {
  // 用户登录
  async login({ commit }, userInfo) {
    const { data } = await login(userInfo)
    commit('SET_TOKEN', data.token)
    console.log(data)
    setToken(data.token)
    return data
  },

  // 用户注册
  async register(_, userInfo) {
    const { data } = await register(userInfo)
    return data
  },

  // 获取用户信息
  async getUserInfo({ commit }) {
    const { data } = await getUserInfo()
    console.log('getUserInfo')
    console.log(data)
    commit('SET_USER_INFO', data)
    return data
  },

  // 退出登录
  async logout({ commit }) {
    return logout().then(() => {
      commit('SET_TOKEN', '')
      commit('SET_USER_INFO', null)
      removeToken()
    }).catch(error => {
      console.error('登出接口调用失败', error)
    })
  },

  async fetchUserList({ commit }, params) {
    const res = await getUserList(params)
    commit('SET_USER_LIST', res.data)
  },

  async addUser(_, data) {
    return addUser(data)
  },

  async updateUser(_, data) {
    return updateUser(data)
  },

  async deleteUser(_, id) {
    return deleteUser(id)
  }
}

const getters = {
  isLoggedIn: state => !!state.token && !!state.userInfo
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}